﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using UstavCSharpServer;

namespace UstavCSharpClient
{
    class UstavClient
    {
        TcpClient client = new TcpClient();

        #region Light codes

        public const int FRONT_LEFT_LIGHT = 1;
        public const int FRONT_RIGHT_LIGHT = 2;
        public const int REAR_LEFT_LIGHT = 4;
        public const int REAR_RIGHT_LIGHT = 8;

        #endregion Light codes

        #region Error codes

        public const int CONNECTION_LOST = 1024;

        #endregion Error codes


        private int lightsCode = 0;

        #region Network

        public int Connect(string IP, int port)
        {
            try
            {
                IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(IP), port);

                client.Connect(serverEndPoint);
            }
            catch
            {
                return 666;
            }

            return 0;
        }

        public int Send(string message)
        {
            if (client.Connected)
            {
                NetworkStream clientStream = client.GetStream();

                ASCIIEncoding encoder = new ASCIIEncoding();
                byte[] buffer = encoder.GetBytes(message);

                clientStream.Write(buffer, 0, buffer.Length);
                clientStream.Flush();
            }
            else
            {
                return CONNECTION_LOST;
            }

            return 0;
        }
        
        public int Send_GO(float latitude, float longitude, float altitude)
        {
            string message = UstavCSharpServer.NetworkMessages.GO(latitude, longitude, altitude);
            return Send(message);
        }

        public int Send_WAIT(int waitTime)
        {
            string message = UstavCSharpServer.NetworkMessages.WAIT(waitTime);
            return Send(message);
        }

        public int Send_LIGHTS(int lightCode, bool on=true)
        {
            // Turn the binary code of the light
            if (on)
                lightsCode |= lightCode;
            else
                lightsCode &= ~lightCode;

            string message = UstavCSharpServer.NetworkMessages.LIGHTS(lightsCode);
            return Send(message);
        }

        #endregion Network
    }
}
